package com.spider.im.common.utils;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Slf4j
public class NetworkUtils {

    /**
     * 获取本地服务的 IP 地址
     *
     * @return 本地服务的 IP 地址
     */
    public static String getLocalIpAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                if (!ni.isLoopback() && ni.isUp()) {
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (!address.isSiteLocalAddress() && !address.isLinkLocalAddress() && !address.isLoopbackAddress()) {
                            return address.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
           log.error("Error getting local IP address: {}", e.getMessage());
        }
        return "127.0.0.1";
    }

    /**
     * 获取客户端的 IP 地址
     *
     * @param ctx ChannelHandlerContext 对象
     * @return 客户端的 IP 地址
     */
    public static String getClientIpAddress(ChannelHandlerContext ctx) {
        if (ctx == null || ctx.channel() == null || ctx.channel().remoteAddress() == null) {
            return "Unknown";
        }
        return ctx.channel().remoteAddress().toString().replace("/", "").split(":")[0];
    }
}